package com.huixh.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huixh.train.business.domain.DailyTrainSeat;
import com.huixh.train.business.domain.DailyTrainSeatExample;
import com.huixh.train.business.domain.TrainSeat;
import com.huixh.train.business.domain.TrainStation;
import com.huixh.train.business.mapper.DailyTrainSeatMapper;
import com.huixh.train.business.req.DailyTrainSeatQueryReq;
import com.huixh.train.business.req.DailyTrainSeatSaveReq;
import com.huixh.train.business.resp.DailyTrainSeatQueryResp;
import com.huixh.train.business.service.DailyTrainSeatService;
import com.huixh.train.business.service.TrainSeatService;
import com.huixh.train.business.service.TrainStationService;
import com.huixh.train.common.resp.PageResult;
import com.huixh.train.utils.random.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author huixh
*/
@Service
public class DailyTrainSeatServiceImpl implements DailyTrainSeatService {

    private final Logger logger = LoggerFactory.getLogger(DailyTrainSeatServiceImpl.class);
    @Resource
    private DailyTrainSeatMapper dailyTrainSeatMapper;
    @Resource
    private TrainSeatService trainSeatService;
    @Resource
    private TrainStationService trainStationService;

    @Resource
    private SnowUtil snowUtil;

    @Override
    public void save(DailyTrainSeatSaveReq dailyTrainSeatSaveReq) {
        DateTime now = DateTime.now();
        DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(dailyTrainSeatSaveReq, DailyTrainSeat.class);
        if (ObjectUtil.isNull(dailyTrainSeat.getId())) {
            dailyTrainSeat.setId(snowUtil.getSnowflakeToLong());
            dailyTrainSeat.setCreateTime(now);
            dailyTrainSeat.setUpdateTime(now);
            dailyTrainSeatMapper.insert(dailyTrainSeat);
        } else {
            dailyTrainSeat.setUpdateTime(now);
            dailyTrainSeatMapper.updateByPrimaryKey(dailyTrainSeat);
        }
    }

    @Override
    public PageResult <List<DailyTrainSeatQueryResp>> queryList(DailyTrainSeatQueryReq dailyTrainSeatQueryReq) {
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.setOrderByClause("train_code asc, carriage_index asc, carriage_seat_index asc");
        DailyTrainSeatExample.Criteria criteria = dailyTrainSeatExample.createCriteria();

        if (StrUtil.isNotBlank(dailyTrainSeatQueryReq.getTrainCode())) {
            criteria.andTrainCodeEqualTo(dailyTrainSeatQueryReq.getTrainCode());
        }

        if (ObjectUtil.isNotNull(dailyTrainSeatQueryReq.getDate())) {
            criteria.andDateEqualTo(dailyTrainSeatQueryReq.getDate());
        }

        logger.info("查询页码：{}", dailyTrainSeatQueryReq.getPageNum());
        logger.info("每页条数：{}", dailyTrainSeatQueryReq.getPageSize());
        PageHelper.startPage(dailyTrainSeatQueryReq.getPageNum(), dailyTrainSeatQueryReq.getPageSize());
        List<DailyTrainSeat> dailyTrainSeatList = dailyTrainSeatMapper.selectByExample(dailyTrainSeatExample);

        PageInfo<DailyTrainSeat> pageInfo = new PageInfo<>(dailyTrainSeatList);
        logger.info("总行数：{}", pageInfo.getTotal());
        logger.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainSeatQueryResp> list = BeanUtil.copyToList(dailyTrainSeatList, DailyTrainSeatQueryResp.class);
        return PageResult.success(pageInfo.getTotal(), list);
    }

    @Override
    public void delete(Long id) {
        dailyTrainSeatMapper.deleteByPrimaryKey(id);
    }

    /**
     * 生成每日车厢座位数据
     *
     * @param trainCode 列车编号
     * @param date      时间
     */
    @Override
    public void genDailySeat(String trainCode, Date date) {

        logger.info("日期【{}】，列车编号：【{}】座位信息生成开始", DateUtil.formatDate(date), trainCode);

        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode);
        dailyTrainSeatMapper.deleteByExample(dailyTrainSeatExample);

        List<TrainSeat> seatListByCode = trainSeatService.getSeatListByCode(trainCode);

        if (CollUtil.isEmpty(seatListByCode)) {
            logger.info("该车次没有基础数据，数据生成失败。");
            return;
        }
        List<TrainStation> trainStations = trainStationService.selectByTrainCode(trainCode);
        StringBuilder sell = new StringBuilder();
        trainStations.forEach(trainStation -> {
            sell.append("0");
        });
        List<DailyTrainSeat> bachelorList = new ArrayList<>(seatListByCode.size());
        for (TrainSeat trainSeat : seatListByCode) {
            DateTime now = DateTime.now();
            DailyTrainSeat dailyTrainSeat = BeanUtil.copyProperties(trainSeat, DailyTrainSeat.class);
            dailyTrainSeat.setId(snowUtil.getSnowflakeToLong());
            dailyTrainSeat.setDate(date);
            dailyTrainSeat.setCreateTime(now);
            dailyTrainSeat.setUpdateTime(now);

            dailyTrainSeat.setSell(sell.toString());
            bachelorList.add(dailyTrainSeat);
            //dailyTrainSeatMapper.insert(dailyTrainSeat);
        }
        dailyTrainSeatMapper.insertBatch(bachelorList);
        logger.info("日期【{}】，列车编号：【{}】座位信息生成结束", DateUtil.formatDate(date), trainCode);
    }
    @Override
    public List<DailyTrainSeat> selectByCarriage(Date date, String trainCode, Integer carriageIndex){
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andCarriageIndexEqualTo(carriageIndex);
        return dailyTrainSeatMapper.selectByExample(dailyTrainSeatExample);
    }

    @Override
    public Long countSeat(Date date, String trainCode) {
        DailyTrainSeatExample trainSeatExample = new DailyTrainSeatExample();
        trainSeatExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode);

        return dailyTrainSeatMapper.countByExample(trainSeatExample);
    }
}